package com.bupt.smart.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.Toast;

import com.bupt.smart.model.recAddress;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.R;
import com.bupt.smart.ui.adapter.AddressAdapter;
import com.bupt.smart.ui.adapter.MarketAdapter;
import com.bupt.smart.ui.widget.FlipperListView;
import com.bupt.smart.ui.widget.ScrollerView;
import com.bupt.smart.utils.MarketHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.Policy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by WWL on 2016/5/31.
 */
public class AddressActivity extends AppCompatActivity implements View.OnClickListener{
    recAddress address;
    int ID  =2;
    MyListView listview_addr;
    FlipperListView flipperListView;
    ScrollerView scroll;
    AddressAdapter adapter_addr;
    ImageView chosenresult;
    ImageView addaddress;
    ImageView address_back;
    View loading;
    Intent getIntent=null;
    private boolean turnFlag = false;
    Context mycontext;
    int addressID=0;
    private List<recAddress> listAddress;
    protected void onCreate( Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        /*this.requestWindowFeature(Window.FEATURE_NO_TITLE);*/
        setContentView(R.layout.activity_addr);
        mycontext = this;
        getIntent = this.getIntent();
        //init widget
        chosenresult = (ImageView)findViewById(R.id.chosenresult);
        addaddress = (ImageView)findViewById(R.id.addaddress);
        address_back = (ImageView)findViewById(R.id.address_back);
        loading = (View)findViewById(R.id.activity_addr_loading);
        flipperListView = (FlipperListView)findViewById(R.id.address_list);
        scroll = (ScrollerView)findViewById(R.id.scroll_flipper);
        scroll.InitScrollerView(mycontext,flipperListView);
        //flipperListView.setContextAndAdapter(this, adapter_addr);
        //获取地址信息
        getAddress(ID);
        //跳转返回订单页面
        address_back.setOnClickListener(this);
        //选择地址跳回订单页面
        chosenresult.setOnClickListener(this);
        //跳转编辑地址界面
        addaddress.setOnClickListener(this);

    }
    /*
    * AddressAdapter回传选定的地址结果
    * @param:AddressAdapter.MyData
    * */
    public void getChoosenAddress(recAddress address){
        this.address = address;
    }
    //改变{确定}按钮状态
    public void changeState(boolean flag){
        if(flag){   //选定结果
            chosenresult.setImageResource(R.mipmap.btn_icon_chosenresult3);//可以跳转
            turnFlag = true;
            Log.i("turnFlag",turnFlag+"");
        }
        else
        {
            chosenresult.setImageResource(R.mipmap.btn_icon_chosenresult2);//不可跳转
            turnFlag = false;
        }
    }
    /*
    * AddressAdapter 加入edit按钮，回调AddressActivity中的函数跳转到地址编辑页面
    *
    * */
    public void address_edit(recAddress address){
        Intent intent = new Intent(AddressActivity.this,AddAddressActivity.class);
        getIntent.putExtras(intent);
        getIntent.putExtra("type", 2);//type=2的跳转是编辑 type=1的跳转是新建地址
        getIntent.putExtra("editAddress", address);//传递地址信息
        getIntent.putExtra("addressID",address.getId());
        intent.putExtras(getIntent);
        AddressActivity.this.startActivity(intent);

    }
    /*
    * 地址删除
    * */
    public void delAddress(int addressId){

        Call<Map<String,Boolean>> call = APIManager.getMarketAPI().delAddress(ID,addressId);
        call.enqueue(new Callback<Map<String, Boolean>>() {
            @Override
            public void onResponse(Call<Map<String, Boolean>> call, Response<Map<String, Boolean>> response) {
                Map<String,Boolean> result;
                if(response.body() != null){
                    result = response.body();
                    if(result.get("result") == true){
                        Toast toast = Toast.makeText(mycontext, "删除成功！", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
                        toast.show();
                        adapter_addr.notifyDataSetChanged();
                    }
                    else {
                        Toast toast = Toast.makeText(mycontext, "删除失败！", Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
                        toast.show();
                    }
                }

            }
            @Override
            public void onFailure(Call<Map<String, Boolean>> call, Throwable t) {
                    Toast toast = Toast.makeText(AddressActivity.this,"连接服务器失败!",Toast.LENGTH_LONG);
                    toast.show();
            }
        });
    }

    /* author:wwl
    * 从后台数据库获取地址的list信息
    * para:
    */
    public void getAddress(int id){
        if(id < 0)  //用户合法性检查
            listAddress = null;
        Call<List<recAddress>> call = APIManager.getMarketAPI().getAddress(id);
        call.enqueue(new Callback<List<recAddress>>() {
            @Override
            public void onResponse(Call<List<recAddress>> call, Response<List<recAddress>> response) {
                if(response.body() != null){
                    listAddress = response.body();
                    //新建地址ID = 现有最大ID+1
                    addressID = 0;
                    recAddress tempData;
                    for(int j=0;j<listAddress.size();j++)
                    {
                        tempData = listAddress.get(j);
                        if(addressID<(tempData.getId()))
                            addressID = tempData.getId();
                    }
                    addressID +=1;//最大ID+1
                }

                else
                    listAddress = null;
                adapter_addr = new AddressAdapter(mycontext,listAddress,flipperListView);
                loading.setVisibility(View.GONE);
                flipperListView.setVisibility(View.VISIBLE);
                adapter_addr.notifyDataSetChanged();
                    /*
                    * setContextAndAdapter(Context,Adapter,Int)
                    * @param:mycontext:当前activity的context
                    * @param:adapter_addr:listview自定义adapter
                    * @param:120:隐藏控件总宽度
                    * */
                flipperListView.setContextAndAdapter(mycontext, adapter_addr,120);
                flipperListView.setAdapter(adapter_addr);
            }
            @Override
            public void onFailure(Call<List<recAddress>> call, Throwable t) {
                Toast toast = Toast.makeText(AddressActivity.this,"获取地址失败",Toast.LENGTH_LONG);
                toast.show();
            }
        });
    }
        //页面跳转
        @Override
        public void onClick(View view){
        switch(view.getId()){
            case R.id.address_back:{    //返回订单界面
                Intent intent = new Intent(AddressActivity.this,OrderActivity.class);
                intent.putExtras(getIntent);
                AddressActivity.this.startActivity(intent);
            }break;
            case R.id.chosenresult:{    //选定地址，返回订单界面
                if(turnFlag==true){ //至少选中一个地址可以跳回OrderActivity
                    Intent intent = new Intent(AddressActivity.this,OrderActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("address", address);
                    getIntent.putExtra("address", bundle);//将收货地址回传到订单详情页面
                    intent.putExtras(getIntent);
                    AddressActivity.this.startActivity(intent);
                }
                else
                {
                    Toast toast = Toast.makeText(getApplicationContext(),"地址不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP|Gravity.CENTER,0,150);
                    toast.show();
                }
            }break;
            case R.id.addaddress:{      //编辑新地址
                Intent intent = new Intent(AddressActivity.this,AddAddressActivity.class);
                getIntent.putExtra("type",1);
                getIntent.putExtra("addressID",addressID);
                intent.putExtras(getIntent);
                AddressActivity.this.startActivity(intent);
            }break;
            default:{}
        }
    }
    }
